package com.letv.android.client.album.controller;

import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.FrameLayout;
import android.widget.FrameLayout.LayoutParams;

import com.letv.android.young.client.R;
import com.letv.android.client.activity.AlbumPlayActivity;
import com.letv.android.client.activity.AlbumPlayRoomActivity;
import com.letv.android.client.utils.LetvBlockLogic;
import com.letv.android.client.utils.LetvBlockLogic.OnBlockCallBack;
import com.letv.android.client.view.BlockDialog;
import com.letv.android.client.view.BlockDialog.BlockDialogCallback;
import com.letv.android.client.view.PlayLoadLayout;
import com.letv.android.client.webview.LetvWebViewActivity;
import com.letv.business.flow.album.AlbumPlayFlow;
import com.letv.business.flow.album.listener.LoadLayoutFragmentListener;
import com.letv.core.bean.VideoBean;
import com.letv.core.constant.LetvConstant.DialogMsgConstantId;
import com.letv.core.constant.PlayConstant;
import com.letv.core.constant.PlayConstant.Authentication;
import com.letv.core.utils.BaseTypeUtils;
import com.letv.core.utils.LogInfo;
import com.letv.core.utils.StatisticsUtils;
import com.letv.core.utils.TipUtils;
import com.letv.core.utils.UIsUtils;
import com.letv.datastatistics.util.PageIdConstant;

import java.util.Collections;

//import com.letv.android.client.controller.ScreenProjectionController.OnPushToTvResponseCallback;
//import com.letv.android.client.controller.ScreenProjectionController.SCREEN_PROJECTION_RESPONSE;
//import com.letv.download.manager.DownloadManager;

/**
 * 点播加载、错误、提示布局控制器
 * 
 * @author zhuqiao
 *
 */
public class AlbumRoomLoadController implements PlayLoadLayout.PlayLoadLayoutCallBack, LoadLayoutFragmentListener, OnBlockCallBack
         {
    private static final String UNDERSTAND = "http://m.lemall.com/products/view/pid-GWGT601006.html?cps_id=le_app_apprx_other_wbqyddtv_";

    /**
     * 用户选择继续缓存，在不退出客户端的情况下，都不再弹出此对话框
     */
    public static boolean sShouldBlockDialog = true;
    /**
     * 是否需要转成横屏后执行投屏操作
     */
    public static boolean sShouldPush = false;

    /** 加载、错误、提示布局 **/
    private PlayLoadLayout mLoadLayout;

    private View mInterputView;

    private AlbumPlayRoomActivity mActivity;
    private LetvBlockLogic mBlockLogic;

    private OnBlockCallBack mBlockCallBack;

    /**
     * 当发生卡顿，并且有视频正在下载则弹出该dialog
     */
    private BlockDialog blockDialog;

    private Handler mHandler = new Handler();

    public AlbumRoomLoadController(AlbumPlayRoomActivity activity, FrameLayout parent) {
        mActivity = activity;
        mLoadLayout = new PlayLoadLayout(activity);
        parent.addView(mLoadLayout, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
        init();
    }

    private void init() {
        mInterputView = mLoadLayout.findViewById(R.id.loadlayout_interput_click);

        mBlockLogic = new LetvBlockLogic(this);
        mLoadLayout.loadingVideo(null);
        mLoadLayout.setCallBack(this);
        mLoadLayout.setLoadingCallBack(new PlayLoadLayout.LoadingCallBack() {

            @Override
            public void loading(boolean show) {
                if (mActivity.getAlbumPlayFragment() != null) {
                    mBlockLogic.onLoading(show, mActivity.getAlbumPlayFragment().getCurrState());
                }
            }
        });

        mInterputView.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // 拦截掉下层事件
            }
        });
    }

    public void noLiveVideo() {
          mLoadLayout.noLiveVideo();
    }

    // --------------------- loadlayout回调 ---------------------

    @Override
    public void loading(boolean show) {
        if (mLoadLayout != null) {
            mActivity.setLoadStatus(true);
            mLoadLayout.loading(show);
        }

    }

    @Override
    public void onRequestErr() {
        if (mActivity.getFlow() != null) {
            mActivity.getFlow().requestErr();
        }
    }

    @Override
    public void onVipErr(boolean isLogin) {
        // do nothing...
    }

    @Override
    public void onJumpErr() {
        if (mActivity.getFlow() == null) {
            return;
        }

        AlbumPlayFlow flow = mActivity.getFlow();
        flow.setCdeStatusCode(-1);
        if (flow.getPlayingVideo() == null) {
            return;
        }

        VideoBean video = flow.getPlayingVideo();
        String type = video.getJumptype();
        if (TextUtils.equals(type, Authentication.WEB_JUMP)) {
            // 提供网页链接按钮
            if (!TextUtils.isEmpty(video.getJumpLink())) {
                if (video.getOpenby() == 1) {
                    // webview打开
                    LetvWebViewActivity.launch(mActivity, video.getJumpLink(), true, false,
                            PlayConstant.LAUNCH_FROM_PLAY_PAGE);
                } else {
                    Uri uri = Uri.parse(video.getJumpLink());
                    Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                    mActivity.startActivity(intent);
                }
            }
        } else if (TextUtils.equals(type, Authentication.TV_JUMP)) {
            // 使用TV投屏观看
            String tip = TipUtils.getTipMessage(mActivity,"100057",
                    mActivity.getString(R.string.dialog_understand_screen_projection));// 了解超级电视
            if (TextUtils.equals(mLoadLayout.getJumpBtnText(), tip)) {
                LetvWebViewActivity.launch(mActivity, TipUtils.getTipMessage(mActivity,"100065", UNDERSTAND), true, false,
                        PlayConstant.LAUNCH_FROM_PLAY_PAGE);
                return;
            }
            if (UIsUtils.isLandscape(mActivity)) {
                if (mActivity.getFullControllerFragment() != null) {
//                    mActivity.getFullControllerFragment().processScreenProjection(mActivity,
//                            ScreenProjectionController.SCR_PROJ_TYPE_PUSH, this);
                }
            } else if (mActivity.getController() != null) {
                sShouldPush = true;
                mActivity.getController().full();
            }
        }
    }

    @Override
    public void onDemandErr() {
        // do nothing...
    }

    @Override
    public void onPlayFailed() {
        // do nothing...
    }

    @Override
    public void calledInError() {
        // zhuqiao dlna
    }

    @Override
    public void calledInFinish() {
        // zhuqiao dlna
    }

    @Override
    public void closeDlna(boolean isStopDlnaPlay) {
        // zhuqiao dlna
    }

    @Override
    public void commitErrorInfo() {
        if (mActivity.getFlow() == null) {
            return;
        }
//        FeedbackUtils.submitFeedbackInfo(mActivity, FeedBackActivity.mContact == null ? "11111111"
//                : FeedBackActivity.mContact, mActivity.getString(R.string.complaintSuccess_block), null,
//                new SimpleResponse<FeedBackBean>() {
//
//                    @Override
//                    public void onNetworkResponse(VolleyRequest<FeedBackBean> request, FeedBackBean result,
//                            DataHull hull, NetworkResponseState state) {
//                        FeedbackUtils.submitCDEExceptionInfo(mActivity, "01234567890",
//                                mActivity.getString(R.string.complaintSuccess_block), null);
//                    }
//
//                });
    }

    // --------------------- 对外提供的接口 ---------------------
    @Override
    public boolean isLoadingShow() {

        if (mLoadLayout != null) {
            if(mLoadLayout.isLoadingShow()) {
                mActivity.setLoadStatus(true);
            } else {
                mActivity.setLoadStatus(false);
            }
            return mLoadLayout.isLoadingShow();
        }
        return false;
    }

    @Override
    public boolean isErrorTagShow() {
        if (mLoadLayout != null)
            return mLoadLayout.isErrorTagShow();
        return false;
    }

    @Override
    public int getErrState() {
        if (mLoadLayout != null)
            return mLoadLayout.getErrState();
        return 0;
    }

    @Override
    public void finish() {
        if (mLoadLayout != null)
            mLoadLayout.finish();
        checkInterput();
    }

    @Override
    public void noPlay() {
        if (mLoadLayout != null)
            mLoadLayout.notPlay();
        checkInterput();
    }

    @Override
    public void requestError(String msg, String errorCode) {
        if (mLoadLayout != null) {
            if (TextUtils.isEmpty(msg)) {
                mLoadLayout.requestError();
            } else if (TextUtils.isEmpty(errorCode)) {
                mLoadLayout.requestError(msg);
            } else {
                mLoadLayout.requestError(msg, errorCode);
            }
        }
        checkInterput();
    }

    @Override
    public void loadingVideo(String name) {
        if (mLoadLayout != null)
            mLoadLayout.loadingVideo(name);
        checkInterput();
    }

    @Override
    public void loadingStart(String loadingMsg, String videoName) {
        if (mLoadLayout != null)
            mLoadLayout.loadingStart(loadingMsg, videoName);
        checkInterput();
    }

    @Override
    public void jumpError(int value) {
        if (mLoadLayout != null) {
            LogInfo.log("zhuqiao", "jumpError");
            if (value == -1) {
                mLoadLayout.jumpError();
            } else {
                mLoadLayout.jumpError(value);
            }
        }
        checkInterput();
    }

    @Override
    public void jumpError(String title, String msg, boolean showBtn) {
        if (mLoadLayout != null) {
            LogInfo.log("zhuqiao", "jumpError");
            mLoadLayout.jumpError(title, msg, showBtn);
        }
        checkInterput();
    }

    @Override
    public void ipError(String msg) {
        if (mLoadLayout != null) {
            mLoadLayout.ipError(msg);
        }
        checkInterput();
    }

    @Override
    public void ipError(String msgTip, boolean isHk) {
        if (mLoadLayout != null) {
            if (TextUtils.isEmpty(msgTip)) {
                mLoadLayout.ipError();
            } else {
                mLoadLayout.ipError(msgTip, isHk);
            }
        }
        checkInterput();
    }

    @Override
    public void autoJumpWeb(VideoBean video) {
        if (video == null) {
            return;
        }

        if (video.getOpenby() == 1) {
            // webview打开
            LetvWebViewActivity.launch(mActivity, video.getJumpLink(), true, false, PlayConstant.LAUNCH_FROM_PLAY_PAGE);
        } else {
            Uri uri = Uri.parse(video.getJumpLink());
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            mActivity.startActivity(intent);
        }
    }

    /**
     * 显示返回、拦截view
     */
    private void checkInterput() {
        if (mActivity == null) {
            return;
        }

        AlbumRoomErrorTopController topController = mActivity.getErrorTopController();
        if (topController == null) {
            return;
        }

        if (isErrorTagShow()) {
            topController.show();
            mInterputView.setVisibility(View.VISIBLE);
            if (mActivity.getFlow() != null && mActivity.getFlow().getPlayingVideo() != null) {
                topController.setTitle(mActivity.getFlow().getPlayingVideo().getNameCn());
            }
        } else {
            topController.hide();
            mInterputView.setVisibility(View.GONE);
        }
    }

    // --------------------- block相关的接口实现 ---------------------
    @Override
    public void commonBlock() {
        if (isDownLoading()) {
            return;
        }

        LogInfo.log("Emerson", "----ssss-------commonBlock");
        blockOccur();
    }

    @Override
    public void blockFiveSeconds() {
        mHandler.post(new Runnable() {

            @Override
            public void run() {
                if (isDownLoading()) {
                    return;
                }

                if (mBlockCallBack != null) {
                    LogInfo.log("Emerson", "----ssss-------blockFiveSeconds");
                    mBlockCallBack.blockSuggest(TipUtils.getTipMessage(mActivity,"100004", R.string.block_suggest_drag_seekbar));
                    mBlockCallBack.blockFiveSeconds();
                }
            }
        });
    }

    @Override
    public void blockSuggest(String msg) {
        // do nothing...
    }

    /**
     * 出现卡顿时执行此方法
     */
    protected void blockOccur() {
        if (mActivity.getFlow() == null) {
            return;
        }
        AlbumPlayFlow flow = mActivity.getFlow();

        if (BaseTypeUtils.isListEmpty(flow.getLevelList())) {
            return;
        }
        Collections.sort(flow.getLevelList());
        // 相对最低码流
        int lowestLevel = flow.getLevelList().get(0);
        LogInfo.log("Emerson", "lowestLevel: " + lowestLevel + "playLevel: " + flow.getPlayLevel());
        if (lowestLevel == flow.getPlayLevel()) {
            if (mBlockCallBack != null) {
                LogInfo.log("Emerson", "----ssss---blockList");
                mBlockCallBack.blockSuggest(TipUtils.getTipMessage(mActivity,"100003", R.string.block_suggest_wait));
                mBlockCallBack.commonBlock();
            }
        } else {
            if (mBlockCallBack != null) {
                LogInfo.log("Emerson", "----ssss---blockList2222");
                mBlockCallBack.blockSuggest(TipUtils.getTipMessage(mActivity,DialogMsgConstantId.BLOCK_SUGGEST_SWITCH_LOW,
                        R.string.block_suggest_switch_low));
            } else {
                LogInfo.log("Emerson", "----ssss---blockList3333");
            }
        }
    }

    public void setOnBlockCallBack(OnBlockCallBack callBack) {
        mBlockCallBack = callBack;
    }

    /**
     * 判断当前是否有视频正在下载
     * 
     * @return
     */
    private boolean isDownLoading() {
//        boolean isDownLoading = DownloadManager.isHasDownloadRunning();
//        LogInfo.log("zhuqiao", "isDownLoading: " + isDownLoading + "LetvSdkPlayerLibs.hasBlockDialogShow: "
//                + sShouldBlockDialog);
//        if (isDownLoading && sShouldBlockDialog) {
//            showBlockDialog();
//            return true;
//        }
        return false;
    }

    private void showBlockDialog() {
        LogInfo.log("zhuqiao", "下载框弹出");
        try {
            if (blockDialog == null) {
                blockDialog = new BlockDialog(mActivity);
                blockDialog.setCanceledOnTouchOutside(false);
            }
            if (blockDialog.isShowing()) {
                return;
            }
            if (mActivity.getFullControllerFragment() != null) {
                mActivity.getFullControllerFragment().setVisibility(View.GONE);
            }
            blockDialog.setCallback(new BlockDialogCallback() {

                @Override
                public void clickButton(boolean pause) {
                    if (!pause) {
                        sShouldBlockDialog = false;
                    }
                    if (mActivity.getFullControllerFragment() != null && UIsUtils.isLandscape(mActivity)) {
                        mActivity.getFullControllerFragment().setVisibility(View.VISIBLE);
                    }
                    if (mActivity.getController() != null) {
                        mActivity.getController().start();
                    }
                }
            });
            blockDialog.setOnCancelListener(new OnCancelListener() {

                @Override
                public void onCancel(DialogInterface dialog) {
                    if (mActivity.getFullControllerFragment() != null && UIsUtils.isLandscape(mActivity)) {
                        mActivity.getFullControllerFragment().setVisibility(View.VISIBLE);
                    }
                    if (mActivity.getController() != null) {
                        mActivity.getController().start();
                    }
                }
            });
            blockDialog.show();
            // 5.7统计
            LogInfo.log("zhuqiao", "暂停缓存弹出框曝光");
            StatisticsUtils.staticticsInfoPost(mActivity, "19", "c68", null, 7, null,
                    UIsUtils.isLandscape(mActivity) ? PageIdConstant.fullPlayPage : PageIdConstant.halpPlayPage, null,
                    null, null, null, null);
            if (mActivity.getController() != null) {
                mActivity.getController().pause(false);
            }

            AlbumPlayActivity.sIsBlockPause = true;
        } catch (Exception e) {
            LogInfo.log("zhuqiao", "下载提示框异常: " + e.getMessage());
            e.printStackTrace();
            AlbumPlayActivity.sIsBlockPause = false;
            sShouldBlockDialog = true;
        }
    }

    public void dismissDialog() {
        if (blockDialog != null && blockDialog.isShowing()) {
            blockDialog.dismiss();
        }
    }

    // ---------------------投屏回调---------------------

//    @Override
//    public void onPushResponse(SCREEN_PROJECTION_RESPONSE result) {
//        if (result == SCREEN_PROJECTION_RESPONSE.PUSH_SUCCESS) {
//            String spTitle = TipUtils.getTipMessage("100052", mActivity.getString(R.string.screen_projection_jump));
//            String spMsg = TipUtils.getTipMessage("100063",
//                    mActivity.getString(R.string.dialog_screen_projection_success));
//            mLoadLayout.jumpError(spTitle, spMsg, false);
//        } else {
//            String spTitle = TipUtils.getTipMessage("100064",
//                    mActivity.getString(R.string.dialog_screen_projection_fail));
//            String spMsg = TipUtils.getTipMessage("100057",
//                    mActivity.getString(R.string.dialog_understand_screen_projection));
//            mLoadLayout.jumpError(spTitle, spMsg, true);
//        }
//    }

    // ------------------------------------------

    public LetvBlockLogic getBlockLogic() {
        return mBlockLogic;
    }

    public void onDestory() {
        if (mBlockLogic != null) {
            mBlockLogic.exitBlockLogic();
        }
    }

}
